<template>
    <el-collapse v-model="activeNames" class="charts-collapse">
        <el-collapse-item v-for="(chart, key) in _charts" :key="key" :title="chart.title" :name="key.toString()">
            <div class="train-charts">
                <canvas :id="chart.canvas_id" class="train-chart"></canvas>
            </div>
        </el-collapse-item>
    </el-collapse>
</template>

<script setup>
import { onMounted, ref, nextTick } from 'vue';

// 定义导出函数、消息
defineExpose({ initCharts, addScalars });

// 引入chart.js库，绘制相关图表
import { Chart, registerables } from 'chart.js';
Chart.register(...registerables);

// charts panel相关属性
const activeNames = ref([]);
let _charts = ref({});
let _charts_ui = {};
let _charts_data = {};

async function clearCharts() {
    for (let chart_id in _charts_ui) {
        let chart = _charts_ui[chart_id];
        chart.ui && (await chart.ui.destroy());
    }

    _charts.value = {};
    await nextTick();
    _charts_ui = {};
    _charts_data = {};
    // console.log('clearCharts completed!');
}

async function initCharts(visConfig) {
    // 清空对应的图表
    await clearCharts();

    // 初始化图表和数据
    let charts = {};
    visConfig.charts.forEach((chart_id) => {
        let chart = visConfig.chart[chart_id];
        let canvas_id = `canvas_${chart_id}`;
        charts[chart_id] = {
            title: chart.title,
            keys: chart.keys,
            canvas_id: canvas_id
        };
    });
    _charts.value = charts;
    activeNames.value = Object.keys(charts);

    // console.log(charts);
    // 等待UI绘制完成
    await nextTick();
    for (let chart_id in _charts.value) {
        let chart = _charts.value[chart_id];
        _charts_ui[chart_id] = initChart(chart.canvas_id, chart.keys, chart.title);
    }
}

function initChart(canvas_id, ylabels, titles) {
    const canvas = document.getElementById(canvas_id);
    canvas.style.width = '550px';
    canvas.style.height = '280px';
    const ctx = canvas.getContext('2d');
    let datasets = ylabels.map((label) => {
        return {
            label: label,
            data: [],
            borderWidth: 2,
            tension: 0
        };
    });
    let chart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: [],
            datasets: datasets
        },
        options: {
            animation: false,
            scales: {
                x: { title: { display: true, text: titles.x } },
                y: { title: { display: true, text: titles.y } }
            },
            plugins: {
                legend: { display: true }
            },
            elements: {
                point: { radius: 0 }
            },
            responsive: false
        }
    });
    return chart;
}

// 根据键名获取对应的数据，并展示到chart控件上
function addScalar(chart, labels, chartData, newData) {
    // console.log(`handleScalar labels = ${labels}, newData = `, newData, 'chartData = ', chartData);
    let has_labels = false;
    labels.forEach((label, index) => {
        if (newData[label] !== undefined) {
            has_labels = true;
            if (!chartData[label]) {
                chartData[label] = [];
            }
            chartData[label].push(newData[label]);
            chart.data.datasets[index].data = chartData[label];
        }
    });
    if (has_labels) {
        chart.data.labels = Array.from({ length: chartData[labels[0]].length }, (_, i) => i + 1);
        chart.update('none');
    }
}

function addScalars(logData) {
    // console.log('handleScalars logData = ', logData);
    let logDataEx = JSON.parse(logData);
    for (let chart_id in _charts.value) {
        let chart = _charts.value[chart_id];
        if (!_charts_data[chart_id]) {
            _charts_data[chart_id] = {};
        }
        addScalar(_charts_ui[chart_id], chart.keys, _charts_data[chart_id], logDataEx);
    }
}

onMounted(async () => {});
</script>

<style scoped>
.charts-collapse {
    padding-left: 10px;
}

.train-charts {
    display: flex;
    justify-content: center;
    background-color: rgb(215, 215, 215);
    padding: 10px;
    height: 300px;
    box-sizing: border-box;
}

.train-chart {
    background-color: white;
    height: 100%;
}
</style>
